<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleAdd"> 新增</a-button>
        <a-button type="primary" @click="editListFn" preIcon="ant-design:plus-outlined" v-if="!startEdit">编辑</a-button>
        <!-- <a-button type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
        <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button> -->
        <a-button type="primary" @click="saveListFn" v-if="startEdit">保存</a-button>
        <a-button type="" @click="editCancel" preIcon="ant-design:close-outlined" v-if="startEdit">取消</a-button>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button>批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
        <!-- 高级查询
        <super-query :config="superQueryConfig" @search="handleSuperQuery" />
         -->
      </template>
      <!--插槽:table说明-->
      <template #tableTop>
        <div class="weight-hint">
          <p class="hint_title">说明</p>
          <ul>
            <li>若方案不参与权重计算，请将该方案权重设置为0（或不填）</li>
            <li>若不设置小数点位数，默认小数点位数为2</li>
            <li v-if="isShowHint" style="color: red">当前方案（方案启用并且参与计算）的权重之和不等于100,建议重新维护权重数据！</li>
          </ul>
        </div>
      </template>
      <!-- 插槽:table表格 -->
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.editRow && column.editComponent === 'Input'">
          <a-input v-if="startEdit" v-model:value="record[column['dataIndex']]" placeholder="请输入方案别称" />
          <span v-else>
            {{ text }}
          </span>
        </template>
        <!-- 开关插槽 -->
        <template v-if="column.editComponent == 'Switch'">
          <a-switch checkedChildren="是" unCheckedChildren="否" :checkedValue="'true'" :unCheckedValue="'false'" size="small" v-model:checked="record[column['dataIndex']]" @change="onSelectChange(record, column['dataIndex'])" />
        </template>
        <!-- 下拉框插槽(折算方式) -->
        <template v-if="column.editRow && column.dataIndex === 'modeCode'">
          <span v-if="!startEdit">
            {{ record['modeName'] }}
          </span>
          <a-select v-else v-model:value="record['modeCode']" style="width: 100%" :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" placeholder="请选择" :fieldNames="{ label: 'modeName', value: 'modeCode' }" :options="conversionModeSelectOptions" allow-clear @change="(e, record) => modeChange(e, record)" />
        </template>
        <!-- 数字输入框插槽(权重,小数点位,满分值) -->
        <template v-if="column.editRow && column.dataIndex === 'weight'">
          <a-input-number v-if="startEdit" v-model:value="record[column['dataIndex']]" addon-after="%" :min="0" />
          <span v-else>
            {{ text }}
          </span>
        </template>
        <template v-if="column.editRow && column.dataIndex === 'decimalPlaces'">
          <a-input-number v-if="startEdit" v-model:value="record[column['dataIndex']]" :min="0" />
          <span v-else>
            {{ text }}
          </span>
        </template>
        <template v-if="column.editRow && column.dataIndex === 'fullScore'">
          <a-input-number v-if="startEdit" v-model:value="record[column['dataIndex']]" addon-after="分" :min="0" />
          <span v-else>
            {{ text }} 分
          </span>
        </template>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <HubTeamCaseOrgModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" name="emp-hubTeamCaseOrg" setup>
import { ref, reactive, onMounted, computed, unref } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { useModal } from '/@/components/Modal';
import { useListPage } from '/@/hooks/system/useListPage'
import HubTeamCaseOrgModal from './components/HubTeamCaseOrgModal.vue'
import { columns, searchFormSchema, superQuerySchema } from './HubTeamCaseOrg.data';
import {list, deleteOne, updateBatch, deleteBatch, getImportUrl, getExportUrl, getConversionModeList, caseStatusChange,caseCountChange,} from './HubTeamCaseOrg.api';
import { Modal } from 'ant-design-vue';
import { useRouter } from 'vue-router';

import { useMessage } from '/@/hooks/web/useMessage'; // 轻提醒
const { createMessage: $message } = useMessage();
const queryParam = reactive<any>({});
const router = useRouter();

//注册model
const [registerModal, { openModal }] = useModal();
//注册table数据
const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    title: '一线班组模块配置-部门个性化',
    api: list,
    columns,
    canResize: false,
    formConfig: {
      //labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,
      fieldMapToNumber: [
      ],
      fieldMapToTime: [
      ],
    },
    actionColumn: {
      width: 200,
      fixed: 'right'
    },
    immediate: true,   //不自动请求
    beforeFetch: (params) => {
      return Object.assign(params, queryParam);
    },
  },
  exportConfig: {
    name: "一线班组模块配置-部门个性化",
    url: getExportUrl,
    params: queryParam,
  },
  importConfig: {
    url: getImportUrl,
    success: handleSuccess
  },
})

const [registerTable, { getForm, reload, getDataSource, setTableData }, { rowSelection, selectedRowKeys }] = tableContext

//权重之和提示
const isShowHint = ref(false);
//控制按钮显示与隐藏
let startEdit = ref(false);
//定义下拉框(折算方式项)
const conversionModeSelectOptions = ref([]);
let orgCodeBase = ref('');

// 默认执行一次
onMounted(async () => {
  //初始化折算方式下拉框
  init();
});

// 获取下拉框数据(折算方式项)
async function init() {
  conversionModeSelectOptions.value = await getConversionModeList();
}

/**
 * 新增事件
 */
function handleAdd() {
  openModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
/**
 * 编辑事件
 */
function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: true,
  });
}
/**
 * 详情
*/
function handleDetail(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: false,
  });
}
/**
 * 删除事件
 */
async function handleDelete(record) {
  await deleteOne({ id: record.id }, handleSuccess);
}
/**
 * 批量删除事件
 */
async function batchHandleDelete() {
  await deleteBatch({ ids: selectedRowKeys.value }, handleSuccess);
}
/**
 * 成功回调
 */
function handleSuccess() {
  (selectedRowKeys.value = []) && reload();
}
/**
 * 表格操作栏
 */
function getTableAction(record) {
  return [
    {
      label: '指标维护',
      onClick: handleIndexConfig.bind(null, record),
    },
    {
      label: '编辑',
      onClick: handleEdit.bind(null, record)
    },
    {
      label: '删除',
      popConfirm: {
        title: '是否确认删除',
        placement: 'left',
        confirm: handleDelete.bind(null, record),
      }
    }
  ]
}

const handleIndexConfig = (record) => {
  if (record.caseCode === 'jichu') {
    router.push({ name: '/zhc/emp/config/HubTeamQuotaOrg', query: { user: '123', role: 'admin' } });
  } else if (record.caseCode === 'index') {
    router.push({ name: 'emp-team-index-HubTeamIndex' });
  } else if (record.caseCode === 'workorder') {
    router.push({ name: 'emp-team-index-HubTeamWork' });
  } else if (record.caseCode === 'addsub') {
    router.push({ name: 'emp-team-index-HubTeamAdd' });
  }
  console.log('record', record);
};

const onSelectChange = (row, dataIndex) => {
  if (startEdit.value) {
    return;
  }
  if (dataIndex === 'caseStatus') {
    // 方案是否启用
    let text = row.caseStatus == 'true' ? '开启' : '关闭';
    Modal.confirm({
      title: '系统提示',
      content: '确认要' + text + '方案吗?',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        caseStatusChange({ id: row.id, isEnable: row.caseStatus });
        reload();
      },
      onCancel: () => {
        row.caseStatus = row.caseStatus == 'true' ? 'false' : row.caseStatus == 'false' ? 'true' : false;
      },
    });
  } else if (dataIndex === 'caseCount') {
    // 方案模块是否参与计算
    let text = row.caseCount == 'true' ? '参与' : '不参与';
    Modal.confirm({
      title: '系统提示',
      content: '确认方案模块' + text + '计算吗?',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        caseCountChange({ id: row.id, isEnable: row.caseCount });
        reload();
      },
      onCancel: () => {
        row.caseCount = row.caseCount == 'true' ? 'false' : row.caseCount == 'false' ? 'true' : false;
      },
    });
  }
};


// 编辑回调
function editListFn() {
  startEdit.value = true;
}

// 保存回调
async function saveListFn() {
  const data = {
    datas: getDataSource(),
    orgCode: orgCodeBase.value,
  };
  nameMapByCode(conversionModeSelectOptions.value, data.datas);
  let num = 0;
  data.datas.forEach((item) => {
    if (item.weight && item.caseCount == 'true' && item.caseStatus == 'true') {
      num += parseFloat(item.weight);
    }
  });
  isShowHint.value = num != 100;
  await updateBatch(data); // 更新数据
  await reload(); // 保存数据
  startEdit.value = false;
}

// 取消回调
async function editCancel() {
  startEdit.value = false;
  let records = getDataSource();
  for (const r of records) {
    try {
      await r.onEdit(false, false);
    } catch (e) { }
  }
  await reload();
  $message.info('已取消');
}

function modeChange(e, record) {
  conversionModeSelectOptions?.value.forEach((item) => {
    if (item.modeCode == e) {
      record.modeName = item.modeName;
    }
  });
}


function nameMapByCode(options, tabList) {
  options.forEach((org) => {
    tabList.forEach((item) => {
      if (item.modeCode == org.modeCode) {
        item.modeName = org.modeName;
      }
    });
  });
}



</script>

<style lang="less" scoped>
:deep(.ant-picker),
:deep(.ant-input-number) {
  width: 100%;
}

.hit_ul {
  padding-left: 28px;
  list-style: disc;
}

.weight-hint {
  // margin: -4px 0 -2px;
  // padding-top: 5px;

  padding: 8px 0 8px 12px;
  // padding-left: 12px;
  // height: 38px;
  background-color: #f3f3f3;
  border-color: #e3e3e3;
  // line-height: 38px;
  color: #a1a1a1;

  p {
    padding: 0;
    margin: 0;
  }
}

.hint_title {
  font-size: 18px;
}
</style>